package com.bawei.lib_common.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import com.bawei.lib_common.R;
import android.graphics.Canvas;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;



public class RedPacketView extends View {

    private Paint bgPaint;//背景
    private Paint fgPaint;//前景进度
    private Paint bitmapPaint;//图片
    private int storkeWidth = 8; // 减小圆环宽度
    //扫描角度
    private int angle = 0;
    //弧形范围
    private RectF rectF = null;
    //图片大小和位置
    private Bitmap bitmap;
    private Rect rect;
    private Rect dst;
    int centerX = 0;
    int centerY = 0;
    private Callback callback = null;
    private ValueAnimator valueAnimator;
    //默认宽高
    private int defaultWidth = 120;//dp转px，减小默认尺寸
    private int defaultHeight = 120;//dp转px，减小默认尺寸
    // 动画时长
    private int animationDuration = 10000;
    // 背景圆环颜色
    private int backgroundCircleColor = Color.rgb(221, 221, 221);
    // 前景圆环颜色
    private int foregroundCircleColor = Color.rgb(255, 0, 51);
    
    // 滑动控制相关
    private boolean isScrolling = false;
    private boolean isAnimating = false;
    private int targetAngle = 0;
    private int currentAngle = 0;
    private static final int SCROLL_ANGLE_INCREMENT = 3; // 减小每次滑动增加的角度
    private boolean hasReachedFull = false; // 是否已经达到过满进度
    private Handler handler = new Handler(Looper.getMainLooper());
    private int fullProgressCount = 0; // 记录满进度次数

    public RedPacketView(Context context) {
        super(context,null);
        initPaint();
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs,0);
        initAttributes(context, attrs);
        initPaint();
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr,0);
        initAttributes(context, attrs);
        initPaint();
    }

    public RedPacketView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttributes(context, attrs);
        initPaint();
    }

    private void initAttributes(Context context, AttributeSet attrs) {
        if (attrs != null) {
            android.content.res.TypedArray typedArray = context.obtainStyledAttributes(attrs, com.bawei.lib_common.R.styleable.RedPacketView);
            try {
                animationDuration = typedArray.getInteger(com.bawei.lib_common.R.styleable.RedPacketView_animationDuration, 10000);
                storkeWidth = typedArray.getDimensionPixelSize(com.bawei.lib_common.R.styleable.RedPacketView_strokeWidth, 8);
                int defaultSize = typedArray.getDimensionPixelSize(com.bawei.lib_common.R.styleable.RedPacketView_defaultSize, 120);
                defaultWidth = defaultSize;
                defaultHeight = defaultSize;
            } finally {
                typedArray.recycle();
            }
        }
    }

    private void initPaint() {
        bgPaint = new Paint();
        bgPaint.setStyle(Paint.Style.STROKE);
        bgPaint.setColor(backgroundCircleColor);
        bgPaint.setStrokeWidth(storkeWidth);
        bgPaint.setAntiAlias(true);

        fgPaint = new Paint();
        fgPaint.setStyle(Paint.Style.STROKE);
        fgPaint.setColor(foregroundCircleColor);
        fgPaint.setStrokeWidth(storkeWidth);
        fgPaint.setAntiAlias(true);

        bitmapPaint = new Paint();
        bitmapPaint.setAntiAlias(true);
        bitmapPaint.setDither(true);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        try {
            // 红包图标尺寸缩小到原来的50%
            int iconSize = Math.min(getMeasuredWidth(), getMeasuredHeight()) / 4;
            bitmap = getBitmap(R.drawable.ic_hongbao, iconSize, iconSize);
            
            if (bitmap != null) {
                int padding = storkeWidth + 2;
                rectF = new RectF(0+padding, 0+padding, getMeasuredWidth()-padding, getMeasuredHeight()-padding);
                centerX = getMeasuredWidth()/2;
                centerY = getMeasuredHeight()/2;

                rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
                dst = new Rect(centerX - bitmap.getWidth()/2, centerY - bitmap.getHeight()/2, centerX+bitmap.getWidth()/2, centerY+bitmap.getHeight()/2);
                
                android.util.Log.d("RedPacketView", "Bitmap loaded successfully: ${bitmap.getWidth()}x${bitmap.getHeight()}");
            } else {
                android.util.Log.e("RedPacketView", "Failed to load bitmap");
            }
        } catch (Exception e) {
            android.util.Log.e("RedPacketView", "Error in onSizeChanged", e);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int withMode = MeasureSpec.getMode(widthMeasureSpec);
        int withSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (withMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(defaultWidth, defaultHeight);
        }else if (withMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(defaultWidth, heightSize);
        }else if (heightMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(withSize, defaultHeight);
        }
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        
        // 只绘制圆环和红包图标，背景透明
        if (bitmap != null && rect != null && dst != null) {
            canvas.drawBitmap(bitmap, rect, dst, bitmapPaint);
        }
        if (rectF != null) {
            canvas.drawArc(rectF, 0, 360, false, bgPaint);
            canvas.drawArc(rectF, 270, angle, false, fgPaint);
        }
    }

    private Bitmap getBitmap(int id, int w, int h){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(),id,options);
        int oldWidth = options.outWidth;
        int oldHeight = options.outHeight;
        int sampleSize = 1;
        while (oldHeight / sampleSize > h || oldWidth / sampleSize > w){
            sampleSize *= 2;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = sampleSize;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap result = BitmapFactory.decodeResource(getResources(), id, options);
        return result;
    }

    /**
     * 开始滑动时的回调
     */
    public void onScrollStart() {
        android.util.Log.d("RedPacketView", "onScrollStart called, previous isScrolling: " + isScrolling);
        isScrolling = true;
        if (!isAnimating) {
            android.util.Log.d("RedPacketView", "Starting scroll animation");
            startScrollAnimation();
        } else {
            android.util.Log.d("RedPacketView", "Animation already running, skipping start");
        }
    }

    /**
     * 滑动过程中的回调
     */
    public void onScroll() {
        if (isScrolling) {
            android.util.Log.d("RedPacketView", "onScroll called, isScrolling: " + isScrolling + ", currentAngle: " + currentAngle + ", targetAngle: " + targetAngle);
            
            // 确保角度只增不减，避免倒退
            int newTargetAngle = targetAngle + SCROLL_ANGLE_INCREMENT;
            
            // 检查是否达到满进度
            if (newTargetAngle >= 360 && !hasReachedFull) {
                hasReachedFull = true;
                fullProgressCount++;
                
                android.util.Log.d("RedPacketView", "Progress will reach full: newTargetAngle=" + newTargetAngle + ", fullProgressCount=" + fullProgressCount);
                
                // 立即设置到满进度，避免倒退
                targetAngle = 360;
                currentAngle = 360;
                angle = 360;
                invalidate();
                
                // 立即触发回调
                if (callback != null) {
                    android.util.Log.d("RedPacketView", "Immediately triggering onProgressFull callback");
                    callback.onProgressFull();
                }
                
                // 停顿100毫秒后重新开始
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        android.util.Log.d("RedPacketView", "Resetting progress after delay");
                        // 重置角度和标志
                        currentAngle = 0;
                        targetAngle = 0;
                        angle = 0;
                        hasReachedFull = false;
                        invalidate();
                        
                        // 如果还在滑动，继续动画
                        if (isScrolling) {
                            startScrollAnimation();
                        }
                    }
                }, 100); // 停顿100毫秒
                
                return; // 不继续更新targetAngle，等待重置
            }
            
            // 正常更新角度，确保不倒退
            if (newTargetAngle > 360) {
                newTargetAngle = newTargetAngle % 360;
            }
            
            // 移除过于严格的倒退检查，允许正常的角度更新
            targetAngle = newTargetAngle;
            
            android.util.Log.d("RedPacketView", "Scroll progress: currentAngle=" + currentAngle + ", targetAngle=" + targetAngle + ", angle=" + angle);
        } else {
            android.util.Log.d("RedPacketView", "onScroll called but isScrolling is false");
        }
    }

    /**
     * 停止滑动时的回调
     */
    public void onScrollStop() {
        android.util.Log.d("RedPacketView", "onScrollStop called, previous isScrolling: " + isScrolling);
        isScrolling = false;
        // 停止动画，保持当前角度
        if (valueAnimator != null && valueAnimator.isRunning()) {
            android.util.Log.d("RedPacketView", "Stopping running animation");
            valueAnimator.cancel();
            isAnimating = false;
        } else {
            android.util.Log.d("RedPacketView", "No running animation to stop");
        }
    }

    /**
     * 开始滑动动画
     */
    private void startScrollAnimation() {
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
        
        isAnimating = true;
        valueAnimator = ValueAnimator.ofInt(currentAngle, targetAngle);
        valueAnimator.setDuration(300); // 更快的动画
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
                currentAngle = (int) valueAnimator.getAnimatedValue();
                angle = currentAngle;
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                isAnimating = false;
                
                android.util.Log.d("RedPacketView", "Animation ended: angle=" + angle + ", hasReachedFull=" + hasReachedFull + ", isScrolling=" + isScrolling);
                
                // 如果还在滑动且未达到满进度，继续动画
                if (isScrolling && !hasReachedFull) {
                    startScrollAnimation();
                }
            }
        });
        valueAnimator.start();
    }

    public void startAnimate(){
        // 如果动画已经在运行，先停止
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
        
        valueAnimator = ValueAnimator.ofFloat(0,1);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                angle = (int)(360*value);
                invalidate();
            }
        });
        valueAnimator.addListener(new AnimatorListenerAdapter(){
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (null != callback){
                    angle = 0;
                    invalidate();
                    callback.completed();
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                    if (null != callback){
                        callback.start();
                    }
            }

            @Override
            public void onAnimationPause(Animator animation) {
                super.onAnimationPause(animation);
                if (null != callback){
                    callback.pause(angle);
                }
            }

            @Override
            public void onAnimationResume(Animator animation) {
                super.onAnimationResume(animation);
                if (null != callback){
                    callback.resume();
                }
            }
        });
        valueAnimator.setDuration(animationDuration);
        valueAnimator.start();
    }

    public void resume(){
        if (null != valueAnimator){
            valueAnimator.resume();
        }
    }

    public void stop(){
        if (null != valueAnimator){
            valueAnimator.cancel();
        }
        isScrolling = false;
        isAnimating = false;
        // 清除所有延迟任务
        handler.removeCallbacksAndMessages(null);
    }

    public interface Callback{
        void start();
        void pause(int angle);
        void resume();
        void completed();
        void onProgressFull(); // 新增：进度满时的回调
    }
    /**
     * 设置监听
     * @param callback
     */
    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    /**
     * 设置动画时长
     * @param duration 动画时长，单位毫秒
     */
    public void setAnimationDuration(int duration) {
        this.animationDuration = duration;
    }

    /**
     * 设置背景圆环颜色
     * @param color 颜色值
     */
    public void setBackgroundCircleColor(int color) {
        this.backgroundCircleColor = color;
        if (bgPaint != null) {
            bgPaint.setColor(color);
            invalidate();
        }
    }

    /**
     * 设置前景圆环颜色
     * @param color 颜色值
     */
    public void setForegroundCircleColor(int color) {
        this.foregroundCircleColor = color;
        if (fgPaint != null) {
            fgPaint.setColor(color);
            invalidate();
        }
    }

    /**
     * 设置圆环宽度
     * @param width 宽度值
     */
    public void setStrokeWidth(int width) {
        this.storkeWidth = width;
        if (bgPaint != null) {
            bgPaint.setStrokeWidth(width);
        }
        if (fgPaint != null) {
            fgPaint.setStrokeWidth(width);
        }
        invalidate();
    }

    /**
     * 获取当前角度
     * @return 当前角度
     */
    public int getCurrentAngle() {
        return angle;
    }

    /**
     * 设置当前角度
     * @param angle 角度值
     */
    public void setCurrentAngle(int angle) {
        this.angle = angle;
        invalidate();
    }

    /**
     * 检查动画是否正在运行
     * @return true表示正在运行，false表示未运行
     */
    public boolean isAnimating() {
        return valueAnimator != null && valueAnimator.isRunning();
    }

    /**
     * 检查是否正在滑动
     * @return true表示正在滑动，false表示未滑动
     */
    public boolean isScrolling() {
        return isScrolling;
    }

    /**
     * 重置进度满标志
     */
    public void resetProgressFullFlag() {
        hasReachedFull = false;
    }

    /**
     * 获取满进度次数
     * @return 满进度次数
     */
    public int getFullProgressCount() {
        return fullProgressCount;
    }

}





























